package com.global.variable.common.web.utils;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * company 重庆庆云石油工程技术有限责任公司
 * FileName WebUtils
 * Package com.basic.management.logic.util
 * Description 浏览器相关工具类
 * author Administrator
 * create 2018-10-17 下午 1:35
 * version V1.0
 */
public class WebUtils extends org.springframework.web.util.WebUtils {

    /**
     * 判断是否ajax 请求
     * @param handlerMethod
     * @return
     */
    public static boolean isAjax(HandlerMethod handlerMethod){
        ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
        if(null != responseBody){
            return true;
        }
        // 获取类上面的Annotation，可能包含组合注解，故采用spring的工具类
        Class<?> beanType = handlerMethod.getBeanType();
        responseBody = AnnotationUtils.getAnnotation(beanType, ResponseBody.class);
        if (null != responseBody) {
            return true;
        }
        return false;
    }


    /**
     * 获得cookie
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name){
        Cookie cookie = getCookie(request,name);
        return cookie != null ? cookie.getValue() : request.getParameter("token");
    }


    /**
     * 清除Coookie
     * @param response
     * @param key
     */
    public static  void removeCookie(HttpServletResponse response, String key){
        setCookie(response, key, null, 0);
    }


    /**
     * 设置Cookie
     * @param response
     * @param name
     * @param value
     * @param maxAgeInSeconds
     */
    public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds){
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAgeInSeconds);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
